import { reactive } from 'vue';
import { PlanParam, StuPlan } from '../types/jobs/planList';
import { ConsoleLogger } from '@/utils/debug-log';
import { getPlanlist } from '@/domain/correction/api/planList/index';
import { router } from '@/project/correction/phoneOa/router';

const console = new ConsoleLogger('讲次列表');

export interface IPlanListState {
  list?: Array<StuPlan>;
  loading: boolean; // 是否加载中，非加载中loading为false,加载中为true
  finished: boolean; // 当finished为true时，不会再触发onLoad事件
  refreshing: boolean; // 当用户下拉时，refreshing自动为true
  waitCorrecList?: Array<StuPlan>;
  correctNum: number;
}

export interface IUsePlanListStore {
  state: IPlanListState;
  toGetPlanlist: () => Promise<void>;
  toClearlist: () => void;
}
/**
 *  * usePlanListStore 讲次列表hooks.
 * @function
 * @params {IPlanListState} userState - 讲次列表信息.
 * @returns store extend IUsePlanListStore
 */
export const usePlanList: () => IUsePlanListStore = () => {
  const state = reactive<IPlanListState>({
    list: [],
    loading: false,
    finished: false,
    refreshing: false,
    waitCorrecList: [],
    correctNum: 0
  });

  const toGetPlanlist = async () => {
    let class_id: any = router.currentRoute.value.query.class_id;
    let course_id: any = router.currentRoute.value.query.course_id;
    if (!state.finished) {
      state.loading = true;
      const data = await getPlanlist({
        class_id: class_id, // 班级id
        course_id: course_id, // 课程id
        work_type: 1 // 请求的作业类型，目前只有1 1 随堂测  3 演说家  4 考试
      });
      state.refreshing = false;
      state.finished = true;
      state.list = state.list?.concat(data.data.list);
      state.waitCorrecList = state.list?.filter((item) => item.correct_num > 0);
      state.correctNum = 0;
      state.waitCorrecList &&
        state.waitCorrecList.map((item) => {
          state.correctNum += item.correct_num;
        });
      state.loading = false;
    }
  };

  const toClearlist = () => {
    state.refreshing = true;
    state.list = [];
    state.finished = false;
  };

  const store: IUsePlanListStore = {
    state,
    toGetPlanlist,
    toClearlist
  };
  return store;
};
